package com.itheima.reggie.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.ISetmealDishService;
import com.itheima.reggie.service.ISetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/setmeal")
@RestController
@Slf4j
@Api(tags = "套餐模块相关的接口")
public class SetmealController {

@Autowired
    ISetmealService setmealService;
@Autowired
    ISetmealDishService setmealDishService;
@Autowired
    ICategoryService categoryService;

    /**
     * 新增套餐接口
     * 注意点:Setmeal ？还是 SetmealDish ? 都不是 创建一个新的实体类：SetmealDto 来封装
     * @param setmealDTO
     * @return
     */
    //修改套餐时,清空setmealCache 缓存名称下的相关的所有的套餐缓存数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody SetmealDTO setmealDTO){
    //1、保存套餐数据到 setmeal表中 ： SetmealMapper
    setmealService.save(setmealDTO);

    //2、保存套餐菜品数据到 setmeal_dish表中： SetmealDishMapper
    //2.1 获取当前套餐的菜品列表
    List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
    //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
    for (SetmealDish setmealDish : setmealDishes) {
        //2.3 获取套餐id，并set到setmealDish中
        setmealDish.setSetmealId(setmealDTO.getId());
        //2.4 保存套餐菜品数据 setmealDish
        setmealDishService.save(setmealDish);
    }
    return R.success("保存套餐成功！！");
}

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation("分页查询套餐数据的接口方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value = "查询的页码",required = true),
            @ApiImplicitParam(name="pageSize",value = "查询的条数",required = true),
            @ApiImplicitParam(name="name",value = "套餐名称,查询条件",required = false)
    })
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
    //用于查询Setmeal分页数据
    Page<Setmeal> setmealPage = new Page<>(page,pageSize);
    //构建条件查询器
    LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
    //设置查询条件
    setmealLambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
    //添加一个排序条件
    setmealLambdaQueryWrapper.orderByDesc(Setmeal::getCreateTime);
    //执行分页查询
     setmealService.page(setmealPage, setmealLambdaQueryWrapper);
        //最终要返回给前端
    Page<SetmealDTO> setmealDTOPage = new Page<>();
    //实现Page<Setmeal> 和 Page<SetmealDTO> 之间属性的对拷(拷贝)
    BeanUtils.copyProperties(setmealPage,setmealDTOPage,"records");
    //写法二 map接口
        List<SetmealDTO> setmealDTOList =setmealPage.getRecords().stream().map(setmeal -> {
            SetmealDTO setmealDTO = new SetmealDTO();
            BeanUtils.copyProperties(setmeal, setmealDTO);
            Category categoryId = categoryService.getById(setmeal.getCategoryId());
            setmealDTO.setCategoryName(categoryId.getName());
            return setmealDTO;
        }).collect(Collectors.toList());
        //将处理完毕后的setmealDTO集合封装到page对象中返回
        setmealDTOPage.setRecords(setmealDTOList);
        return R.success(setmealDTOPage);
    }

    /**
     *删除套餐
     * @param ids
     * @return
     */
    //修改套餐时,清空setmealCache 缓存名称下的相关的所有的套餐缓存数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    public R<String> delete(@RequestParam List <Long> ids){
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.in(Setmeal::getId,ids);
        setmealWrapper.eq(Setmeal::getStatus,1);

        int count = setmealService.count(setmealWrapper);
        if (count>0){
            return R.error("删除失败");
        }else {
            setmealService.removeByIds(ids);
            return R.success("套餐删除成功");
        }
    }

    /**
     * 起售/停售套餐
     * @param ids
     * @param status
     * @return
     */
    //修改套餐时,清空setmealCache 缓存名称下的相关的所有的套餐缓存数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateIds(@RequestParam List<Long> ids,@PathVariable Integer status){
        LambdaUpdateWrapper<Setmeal> setmealLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        setmealLambdaUpdateWrapper.set(Setmeal::getStatus,status).in(Setmeal::getId,ids);
        setmealService.update(setmealLambdaUpdateWrapper);
        return R.success("操作成功");
    }

    /**
     * 根据套餐id查询套餐数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
     public R<SetmealDTO> queryOne(@PathVariable Long id){
        //1、根据套餐id查询套餐数据
        Setmeal setmealbyId = setmealService.getById(id);
        //2、根据套餐id查询套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDTO setmealDTO = new SetmealDTO();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmealbyId,setmealDTO);
        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDTO.setSetmealDishes(setmealDishList);
        //4、返回 setmealDto
        return R.success(setmealDTO);
    }

    /**
     * 修改套餐
     * @param setmealDTO
     * @return
     */
    //修改套餐时,清空setmealCache 缓存名称下的相关的所有的套餐缓存数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    public R<String> updateSetmeal(@RequestBody SetmealDTO setmealDTO){
        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?
        setmealService.updateById(setmealDTO);
        //2、操作套餐对应的菜品数据： setmeal_dish
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        // 获取套餐id   setmealDto.getId()
        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDTO.getId());
        setmealDishService.remove(queryWrapper);
        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        /*// 遍历套餐菜品集合数据
        for (SetmealDish setmealDish : setmealDishes) {
            // 有没有数据需要set ： 设置套餐id  setSetmealId
            setmealDish.setSetmealId(setmealDTO.getId());
            // 添加套餐菜品数据 insert*/
        List<SetmealDish> setmealDishList = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDTO.getId());
            return setmealDish;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishList);
        return R.success("修改套餐成功");

    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    //功能比较单一:将方法的返回结果存储到缓存中
    //@CachePut(value = "setmealCache",key="'setmeal_'+#setmeal.categoryId")
    //功能更强大:先查询缓存是否存在指定key的数据,如果存在直接返回缓存数据:不存在,正常执行方法将方法返回结果存储到缓存中
    @Cacheable(value = "setmealCache",key = "'setmeal_'+#setmeal.categoryId",unless = "#result == null")
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);

    }

}
